package news.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import news.dao.AdminDao;
import news.model.Admin;
import news.model.CommonResult;
import news.model.Role;
import news.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
@Transactional
public class AdminService {

    @Autowired(required = false)
    AdminDao adminDao;

    public PageInfo<Admin> adminList(Admin admin){

        // pageNum当前页面  pageSize每页大小
        PageHelper.startPage(admin.getPageNum(), admin.getPageSize());
        List<Admin> admins = adminDao.adminList(admin);
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        return pageInfo;
    }

    public List<Role> roles() {
        return adminDao.roles();
    }

    public void save(Admin admin, String adminToken) {
        //1.从token中解析出管理员id
        admin.setAdmin(JWTUtil.getAdminByToken(adminToken));
        //2.生成默认密码，并给密码加密
     /*   String password = admin.getPhone();//获取新操作员的电话号码
        String pwd = password.substring(5);//从第五位开始截取到最后作为默认密码
        String enPwd = DigestUtils.md5DigestAsHex(pwd.getBytes());//调用DigestUtils.md5DigestAsHex()方法对密码进行加密
        admin.setPassword(enPwd);//把新生成的密码加进去
        */
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPhone().substring(5).getBytes()));

        //3.保存管理员信息到数据库

        adminDao.save(admin);

        //4.保存管理员id和角色id到admin_role表中

        for(Integer roleId : admin.getRoleId()){
            adminDao.saveAdminRole(roleId,admin.getId());
        }
    }

    public void delete(Integer id) {
        adminDao.deleteAdmin(id);

        adminDao.deleteAdminRole(id);
    }

    public Admin findAdminById(Integer id) {
        Admin admin = adminDao.findAdminById(id);
        //将一个管理员对应的多个角色id从集合中转换到一个数组中
        Integer[] roleId = new Integer[admin.getRoles().size()];
        int i = 0;
        for(Role role : admin.getRoles()){
            roleId[i++] = role.getId();
        }
        admin.setRoleId(roleId);
        return admin;
    }

    public void update(Admin admin, String adminToken) {
        //1.从token中解析出管理员的id
        admin.setAdmin(JWTUtil.getAdminByToken(adminToken));
        //2.修改管理员信息
        adminDao.update(admin);
        //3.删除管理员和角色之间的关系
        adminDao.deleteAdminRole(admin.getId());
        //4/添加管理员和角色之间的关系
        for(Integer roleId : admin.getRoleId()){
            adminDao.saveAdminRole(roleId,admin.getId());
        }
    }

    public void changePwd(String password) {
        String s = DigestUtils.md5DigestAsHex(password.substring(5).getBytes());
        adminDao.changePwd(s);
    }
}
